package com.jianbing.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jianbing.http.HttpAsynClient;
import com.jianbing.http.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.net.URLEncoder;
import java.util.Date;

/**
 * Created by Han, Tixiang on 2016/8/29 0029.
 */
public class SMSMessageHelper {
    private static Log log = LogFactory.getLog(SMSMessageHelper.class);

    public static boolean sendMessage(String content) {
        if (StringUtils.isEmpty(content)) {
            return false;
        }
        String tels = PropertiesUtils.getProperties("NOTIFY_USER_PHONE");
        return sendDuorenMessage(tels, content);
    }

    public static boolean sendDuorenMessage(String phones, String content) {
        if (StringUtils.isEmpty(phones) || StringUtils.isEmpty(content)) {
            return false;
        }
        String[] telsArr = phones.split(",");
        boolean flag = false;
        for (int i = 0; i < telsArr.length; i++) {
            flag = SMSMessageHelper.sendMessage(telsArr[i], content);
        }
        return flag;
    }

    public static boolean sendMessage(String[] phones, String content) {
        boolean flag = false;
        if (phones == null || StringUtils.isEmpty(content)) return false;
        for (int i = 0; i < phones.length; i++) {
            flag = SMSMessageHelper.sendMessage(phones[i], content);
        }
        return flag;
    }

    public static boolean sendMessage(String phones, String content) {

        //短信接口URL提交地址
        String url = PropertiesUtils.getProperties(JianbingConstants.JIANBING_SMS_URL);
        if (StringUtils.isEmpty(url) || StringUtils.isEmpty(content)) {
            return false;
        }

        JSONObject object = new JSONObject();
        object.put("type", "3005");
        object.put("server_tag", "ROBOT_GJJ");
        object.put("phone", phones);
        object.put("expect_time", "0");
        object.put("user_sid", "0");
        object.put("req_time", new Date());
        object.put("content", content);

        try {
            url = url + URLEncoder.encode(object.toJSONString(), "UTF-8");
            String result = HttpAsynClient.doGet(url);
            log.info(result);
            if (!StringUtils.isEmpty(result)) {
                JSONObject obj = JSON.parseObject(result);
                if (obj.get("resp").equals("ok")) {
                    log.info("send message  to " + phones + " successfully ,the message is :" + content);
                    return true;
                }
            }
            log.info("send message  to " + phones + " fail ,the message is :" + content);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return false;
    }

    public static void main(String[] args) {
    }
}
